package servlet;

import entity.Emp;
import util.ParameterUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author 石小俊
 */
@WebServlet("*.emp")
public class EmpServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        req.setCharacterEncoding("utf-8");
        PrintWriter out = resp.getWriter();
        String servletPath = req.getServletPath();
        System.out.println("servletPath:" + servletPath);
        switch (servletPath) {
            case "/add.emp":
                addEmp(req, resp);
                break;
            case "/findAll.emp":
                findAll(req, resp);
                break;
            case "/findById.emp":
                showModifyEmp(req, resp);
                break;
            case "/modify.emp":
                modifyEmp(req, resp);
                break;
            case "/delete.emp":
                deleteEmp(req, resp);
                break;
            default:
                out.println("<h1 style='color:red;'>对不起,您访问的资源不存在,请检查地址是否正确</h1>");
                break;
        }
    }

    public void addEmp(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name");
        String salary = req.getParameter("salary");
        String gender = req.getParameter("gender");
        String edu = req.getParameter("edu");
        String[] hobbies = req.getParameterValues("hobbies");
        System.out.println("name:" + name + ",salary:" + salary + ",gender:" + gender + ",edu:" + edu + ",hobbies:" + Arrays.toString(hobbies));

        Connection conn = null;
        PreparedStatement ps = null;
        try {
            // JDBC操作
            // 1.注册驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            // 2.获取连接
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/web?useUnicode=true&characterEncoding=utf-8", "root", "root");
            // 3.获取状态集
            String sql = new StringBuffer()
                    .append(" insert into ")
                    .append(" t_emp(name,salary,gender,edu,hobbies)")
                    .append(" values(?,?,?,?,?)")
                    .toString();
            ps = conn.prepareStatement(sql);
            // 设置参数
            ps.setString(1, name);
            ps.setDouble(2, Double.parseDouble(salary));
            ps.setString(3, gender);
            ps.setString(4, edu);
            ps.setString(5, ParameterUtil.arrayToString(hobbies));

            // 4.执行sql
            ps.executeUpdate();

            // 重定向
            resp.sendRedirect(req.getContextPath()+"/findAll.emp");
        } catch (ClassNotFoundException e) {
            req.setAttribute("empMsg","未注册驱动");
            // 转发不需要应用名,开头的/表示的是应用名后面的/
            req.getRequestDispatcher("/ems/addEmp.jsp").forward(req,resp);
        } catch (SQLException e) {
            req.setAttribute("empMsg","数据访问异常");
            req.getRequestDispatcher("/ems/addEmp.jsp").forward(req,resp);
        } catch (Exception e) {
            e.printStackTrace();
            req.setAttribute("empMsg","服务器内部异常");
            req.getRequestDispatcher("/ems/addEmp.jsp").forward(req,resp);
        } finally {
            // 6.释放资源
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    req.setAttribute("empMsg","释放连接失败");
                    req.getRequestDispatcher("/ems/addEmp.jsp").forward(req,resp);
                }
            }
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    req.setAttribute("empMsg","释放状态集失败");
                    req.getRequestDispatcher("/ems/addEmp.jsp").forward(req,resp);
                }
            }
        }
    }

    public void findAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        List<Emp> emps = new ArrayList<>();
        try {
            // 根据主键查询员工信息
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/web?useUnicode=true&characterEncoding=utf-8", "root", "root");
            String sql = new StringBuffer()
                    .append(" select id,name,salary ")
                    .append(" from t_emp ")
                    .toString();
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            while (rs.next()){
                Emp emp = new Emp();
                emp.setId(rs.getInt("id"));
                emp.setName(rs.getString("name"));
                emp.setSalary(rs.getDouble("salary"));
                emps.add(emp);
            }
            // 此时后端已经查询出需要的数据,如何将这些数据传递到JSP页面?
            // 在请求对象中提供了存储数据与获取数据的方式
            // setAttribute(String key,Object value):在请求中存储一组数据
            // getAttribute(String key):从请求中获取指定key的数据
            // 在存储数据与获取数据的时候,有一个注意点
            // 重要的注意点:必须是同个请求才能取出存储的数据
            // 如果页面跳转到JSP后想要获取此处在请求中存储的数据
            // 那么必须保证跳转的JSP页面与当前Servlet是共享请求的
            req.setAttribute("emps",emps);
            req.getRequestDispatcher("/ems/empList.jsp").forward(req,resp);

        } catch (ClassNotFoundException e) {
            throw new RuntimeException("未找到驱动");
        } catch (SQLException e) {
            throw new RuntimeException("数据访问异常");
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    throw new RuntimeException("释放连接失败");
                }
            }
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    throw new RuntimeException("释放状态集失败");
                }
            }
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    throw new RuntimeException("释放结果集失败");
                }
            }
        }
    }

    public void showModifyEmp(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        Emp emp = null;
        try {
            // 根据主键查询员工信息
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/web?useUnicode=true&characterEncoding=utf-8", "root", "root");
            String sql = new StringBuffer()
                    .append("select id,name,salary,gender,edu,hobbies ")
                    .append(" from t_emp ")
                    .append(" where id = ? ")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setInt(1, Integer.parseInt(id));
            rs = ps.executeQuery();
            if (rs.next()) {
                emp = new Emp();
                emp.setId(rs.getInt("id"));
                emp.setName(rs.getString("name"));
                emp.setSalary(rs.getDouble("salary"));
                emp.setGender(rs.getString("gender"));
                emp.setEdu(rs.getString("edu"));
                emp.setHob(rs.getString("hobbies"));
            }
            req.setAttribute("emp",emp);
            req.getRequestDispatcher("/ems/modifyEmp.jsp").forward(req,resp);
        } catch (ClassNotFoundException e) {
            req.setAttribute("empMsg","未注册驱动");
            req.getRequestDispatcher("/findAll.emp").forward(req,resp);
        } catch (SQLException e) {
            req.setAttribute("empMsg","数据访问异常");
            req.getRequestDispatcher("/findAll.emp").forward(req,resp);
        } catch (Exception e) {
            e.printStackTrace();
            req.setAttribute("empMsg","服务器内部异常");
            req.getRequestDispatcher("/findAll.emp").forward(req,resp);
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    throw new RuntimeException("释放连接失败");
                }
            }
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    throw new RuntimeException("释放状态集失败");
                }
            }
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    throw new RuntimeException("释放结果集失败");
                }
            }
        }
    }

    public void modifyEmp(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取请求参数
        String id = req.getParameter("id");
        String name = req.getParameter("name");
        String salary = req.getParameter("salary");
        String gender = req.getParameter("gender");
        String edu = req.getParameter("edu");
        String[] hobbies = req.getParameterValues("hobbies");

        // JDBC实现修改操作
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            // 根据主键查询员工信息
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/web?useUnicode=true&characterEncoding=utf-8", "root", "root");
            String sql = new StringBuffer()
                    .append(" update t_emp ")
                    .append(" set ")
                    .append("   name = ?, ")
                    .append("   salary = ?, ")
                    .append("   gender = ?, ")
                    .append("   edu = ?, ")
                    .append("   hobbies = ? ")
                    .append(" where id = ? ")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setString(1, name);
            ps.setDouble(2, Double.parseDouble(salary));
            ps.setString(3, gender);
            ps.setString(4, edu);
            ps.setString(5, ParameterUtil.arrayToString(hobbies));
            ps.setInt(6, Integer.parseInt(id));

            ps.executeUpdate();

            // 重定向到员工列表
            resp.sendRedirect(req.getContextPath()+"/findAll.emp");

        } catch (ClassNotFoundException e) {
            req.setAttribute("empMsg","未注册驱动");
            req.getRequestDispatcher("/findById.emp?id="+id).forward(req,resp);
        } catch (SQLException e) {
            req.setAttribute("empMsg","数据访问异常");
            req.getRequestDispatcher("/findById.emp?id="+id).forward(req,resp);
        } catch (Exception e) {
            e.printStackTrace();
            req.setAttribute("empMsg","服务器内部异常");
            req.getRequestDispatcher("/findById.emp?id="+id).forward(req,resp);
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    throw new RuntimeException("释放连接失败");
                }
            }
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    throw new RuntimeException("释放状态集失败");
                }
            }
        }
    }

    public void deleteEmp(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            // 通过JDBC实现删除功能
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/web?useUnicode=true&characterEncoding=utf-8","root","root");
            String sql = new StringBuffer()
                    .append(" delete from t_emp ")
                    .append(" where id = ? ")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setInt(1,Integer.parseInt(id));
            ps.executeUpdate();
            // 删除成功之后跳转到员工列表
            resp.sendRedirect(req.getContextPath()+"/findAll.emp");
        } catch (Exception e) {
            req.setAttribute("empMsg","服务器内部异常");
            req.getRequestDispatcher("/findAll.emp").forward(req,resp);
        }
    }
}
